package main

import (
	"io"
	"log"
	"net"
	"strings"
	"time"
)

//处理不同类型的请求
func hander(conn net.Conn) {
	buf := make([]byte, 1024)
	n, err := conn.Read(buf)
	if err != nil {
		if err != io.EOF {
			log.Printf("conn.Read()方法执行出错，错误为:%v\n", err)
		}
		return
	}
	//获取操作类型
	slice := strings.Split(string(buf[:n]), ",")
	if len(slice) == 1 && slice[0] == "list" {
		log.Println("接受到list请求")
		strs := GetFilesInfo()
		s := strings.Join(strs, "\n")
		conn.Write([]byte(s))
	} else if len(slice) == 2 && slice[0] == "upload" {
		RecvFile(conn, slice[1])
		UpdateFileMate(slice[1], time.Now().Format("2006-01-02 15:04"))
	} else if len(slice) == 2 && slice[0] == "download" {
		SendFile(conn, slice[1])
	}
}

func main() {
	//1.创建监听socket
	listener, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		log.Printf("net.Listen()函数执行错误，错误为:%v\n", err)
		return
	}
	defer listener.Close()
	log.Println("Runing:")
	for {
		//阻塞监听
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("listener.Accept()方法执行错误，错误为:%v\n", err)
			return
		}
		go func(conn net.Conn) {
			defer conn.Close()
			hander(conn)
		}(conn)
	}
}
